package com.net;

public class MyThreadRun {
  public static void main(String[] args) {
//    MyThread myThreadA = new MyThread("A");
//    myThreadA.start();
//
//    MyThread myThreadB = new MyThread("B");
//    myThreadB.start();
//
//    MyThread myThreadC = new MyThread("C");
//    myThreadC.start();


    MyThreadShareParamater shareParamater = new MyThreadShareParamater();

    Thread threadA = new Thread(shareParamater, "A");
    Thread threadB = new Thread(shareParamater, "B");
    Thread threadC = new Thread(shareParamater, "C");
    Thread threadD = new Thread(shareParamater, "D");
    Thread threadE = new Thread(shareParamater, "E");

    threadA.start();
    threadB.start();
    threadC.start();
    threadD.start();
    threadE.start();


    System.out.println("线程运行结束！");
  }

}

/**
 * 继承 thread类 并重写run方法
 * 变量不共享 非线程安全的
 */
class MyThread extends Thread {

  private int count = 5;

  public MyThread(String name) {
    super();
    this.setName(name);
  }

  @Override
  public void run() {
    while (count > 0) {
      super.run();
      count--;
      System.out.println("由 mythread run ..." + this.currentThread().getName()+ "计算,count= "+count);

    }

  }
}

/**
 * 共享变量
 */
class MyThreadShareParamater extends Thread {

  private int count = 5;

  /**
   * 添加上synchronized(可以在任意对象和方法上加锁，加锁的代码成为"互斥区","临界区" ) 使该线程为线程安全
   * 当一个线程调用run方法钱，先判断run方法有没有被上锁， 如果上锁了，说明有其他线程在调用run方法，必须等待线程对run
   * 方法调用结束后才可以执行run方法
   */
  @Override
  synchronized public void run() {
    super.run();
    count--;
    System.out.println("由 " + this.currentThread().getName() + " 计算, count=" + count);
  }
}


